/**
 * 
 */
package com.atung.service.impl;

import java.math.BigDecimal;
import java.time.Instant;
import java.util.Map;
import java.util.Random;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.atung.config.wx.MyJSConfig;
import com.atung.config.wx.WxPayConfig;
import com.atung.dao.BusOrderRefundDAO;
import com.atung.dao.BusOrederCarLCDAO;
import com.atung.exceptiom.LcExceptionEnum;
import com.atung.model.BusOrderRefund;
import com.atung.model.RefundDO;
import com.atung.request.RequestRefund;
import com.atung.service.WXPayService;
import com.atung.tool.SnowflakeIdWorker;
import com.github.wxpay.sdk.WXPay;
import com.google.common.base.Objects;
import com.yuyi.full.Result;

import ch.qos.logback.core.joran.conditional.IfAction;

/**
 * 
 * @author lc <br>
 * 2020年11月17日 下午2:59:11
 */
@Service
public class WXPayServiceImpl implements WXPayService {
    
    @Autowired
    private BusOrederCarLCDAO busOrederCarLCDAO;
    
    @Autowired
    private BusOrderRefundDAO busOrderRefundDAO; 
    
    @Override
    @Transactional
    public Result<?> refund(RequestRefund red) throws Exception {
        //查询退款表
        BusOrderRefund byOrderId = busOrderRefundDAO.getByOrderId(red.getOrderId());
        if (byOrderId !=null) {
            return Result.error(LcExceptionEnum.ORDER_STATE_ERRO);
        }
        //获取订单信息。。。。。
        RefundDO order = busOrederCarLCDAO.getById(red.getOrderId(),red.getOpenId());
        if (order == null) {
            return Result.error(LcExceptionEnum.ORDER_ERRO);
        }
        //判断订单信息是否为已支付订单
        if (order.getOrderStatus() != 202) {
           return Result.error(LcExceptionEnum.ORDER_STATE_ERRO);
        }
        if (order.getOrderState()!= 300 ||order.getOrderState()!= 301) {
            return Result.error(LcExceptionEnum.TRAVLE_REFUND_ERRO);
        }
        
        //如果为已支付订单 判断线路是否超出规定时间  如果已经超出规定时间  判断退款金额
        BigDecimal money = order.getOrderPayMoney();
        BigDecimal totalFee = money.multiply(new BigDecimal(100.00));
        BigDecimal refundFee = totalFee;
        Instant startTime = busOrederCarLCDAO.getRouteStartTime(order.getRoutPublishId());
        //三天后时间
        Instant refund = Instant.now();
        Instant requestTimeUtc = refund.plusMillis(TimeUnit.DAYS.toMillis(3));
        if(startTime.toEpochMilli() < requestTimeUtc.toEpochMilli()){
            refundFee = money.multiply(new BigDecimal(0.50));
        }
        
        //添加退款表
        BusOrderRefund busOrderRefund = new BusOrderRefund();
        busOrderRefund.setOrderId(red.getOrderId());
        busOrderRefund.setOpenId(red.getOpenId());
        busOrderRefund.setRefundFee(refundFee.multiply(new BigDecimal(0.01)));
        busOrderRefund.setTotalFee(money);
        busOrderRefund.setRefundState(400);
        busOrderRefund.setRefundDesc(red.getRefundDesc());
        busOrderRefund.setRefundTime(refund);
        busOrderRefund.setRoutStartTime(startTime);
        
        busOrderRefundDAO.insert(busOrderRefund);
        //修改订单状态为退款中
        busOrederCarLCDAO.updateOrderRefund(order.getId());
        busOrederCarLCDAO.updatePublishRefund(order.getId());
        return Result.success();
    }
    
    

//    @Override
//    @Transactional
//    public Result<?> refund1(RequestRefund red) throws Exception {
//        
//        //获取订单信息。。。。。
//        RefundDO order = busOrederCarLCDAO.getById(red.getOrderId(),red.getOpenId());
//        if (order == null) {
//            return Result.error(LcExceptionEnum.ORDER_ERRO);
//        }
//        //判断订单信息是否为已支付订单
//        if (order.getOrderStatus() != 202) {
//           return Result.error(LcExceptionEnum.ORDER_STATE_ERRO);
//        }
//        if (order.getOrderState()!= 300 ||order.getOrderState()!= 301) {
//            return Result.error(LcExceptionEnum.TRAVLE_REFUND_ERRO);
//        }
//        //如果为已支付订单 判断线路是否超出规定时间  如果已经超出规定时间  判断退款金额
//        BigDecimal money = order.getOrderPayMoney();
//        BigDecimal totalFee = money.multiply(new BigDecimal(100.00));
//        BigDecimal refundFee = totalFee;
//        Instant startTime = busOrederCarLCDAO.getRouteStartTime(order.getRoutPublishId());
//        //三天后时间
//        Instant requestTimeUtc = Instant.now().plusMillis(TimeUnit.DAYS.toMillis(3));
//        if(startTime.toEpochMilli() < requestTimeUtc.toEpochMilli()){
//            refundFee = money.multiply(new BigDecimal(0.50));
//        }
//        MyJSConfig config = new MyJSConfig();
//        WXPay wxpay = new WXPay(config);
//        
//        Long refundId=SnowflakeIdWorker.nextId();
//        SortedMap<String,String> paramMap = new TreeMap<String,String>();
//        paramMap.put("out_trade_no", order.getId().toString());
//        paramMap.put("out_refund_no",  refundId.toString());
//        //金额（“分”）
//        paramMap.put("total_fee", totalFee.toString());
//        paramMap.put("refund_fee", refundFee.toPlainString());
////        paramMap.put("notify_url", "回调");
//        Map<String, String> refund = wxpay.refund(paramMap);
//        
//        String returnmsg = (String) refund.get("result_code");
//        BusOrderRefund bo = new BusOrderRefund();
//        bo.setId(red.getOrderId());
//        bo.setRefundId(refundId);
//        bo.setRefundFee(refundFee.multiply(new BigDecimal(0.01)));
//        bo.setTotalFee(money.multiply(new BigDecimal(0.01)));
//        //判断退款是否成功
//        if ("SUCCESS".equals(returnmsg)) {
//            bo.setRefundState(305);
//            bo.setWxRefund(refund.get("refund_id"));
//            busOrederCarLCDAO.updateOrderRefund(order.getId());
//            busOrederCarLCDAO.updatePublishRefund(order.getId());
//            
//        }else{
//            bo.setRefundState(306);
//            return Result.error(LcExceptionEnum.ORDER_REFUND_ERRO);
//        }
//        busOrderRefundDAO.insert(bo);
//        return Result.success();
//    }

}
